package org.i1510.common.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;

import org.i1510.common.bean.PageBean;
import org.i1510.common.bean.SessionUserBean;
import org.i1510.common.dao.ISysUserDao;
import org.i1510.common.po.SysPop;
import org.i1510.common.po.SysUser;
import org.i1510.common.service.ISysPopService;
import org.i1510.common.service.ISysUserService;
import org.i1510.common.utils.BeanUtils;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.KBProperties;
import org.i1510.common.utils.PrintWriterUtils;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.encryption.Md5;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;






@Controller
@RequestMapping(value = "/admin")
public class SysUserController {
	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
	@Autowired
	private ISysUserService iSysUserService;
	@Autowired
	private ISysUserDao iSysUserDao;

	@Autowired
	private ISysPopService iSysPopService;
	
	private ResultMapper mapper;
	
	
	/**
	*@Author Rambo
	*@Desc：注销
	*@param system spring必须带有参数
	*@param request
	*@param response
	*@param session
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2016年7月21日 下午3:47:06 
	*/
	@RequestMapping(value = "/out", method ={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public String out(@ModelAttribute("system") String system,HttpServletRequest request,HttpServletResponse response,
			HttpSession session,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			
			session.invalidate();
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("message", "注销成功!");
			
		}
		try {
			response.sendRedirect(KBProperties.WEBSITE_URL+"/common/login/login.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping(value = "/sysUser/findMenu", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String findMenu(HttpServletRequest request,
			HttpServletResponse response,
			@Valid @ModelAttribute("sysPop") SysPop sysPop, BindingResult errors) {
		
		
		PrintWriterUtils write = new PrintWriterUtils();
		write.sendPrintWriterUtils(response, UserUtils.getSessionUserBean(request).getMenuJson(), "json");
		return null;

	}
	/**
	*@Author Rambo
	*@Desc：登录控制
	*@param sysUser
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2013-11-21 下午5:38:15 
	*/
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public String login(HttpServletRequest request,HttpSession session,@ModelAttribute("system") String system,@ModelAttribute("validCode") String validCode,@ModelAttribute("name") String userName,@ModelAttribute("pwd") String userPw,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			mapperRtn = ResultMapper.generateSuccess();
//			Object obj = session.getAttribute(Captcha.NAME);
//			if(null != obj){
//				Captcha captcha = (Captcha) obj;				
//				if(captcha.isCorrect(validCode)){
					SysUser findUser = iSysUserDao.findByPwAndName(Md5.getPassword(userPw), userName.toLowerCase().trim());
					if(null != findUser){
						SysUser sysUser = new SysUser();
						BeanUtils.copy(sysUser, findUser);
						if(sysUser.getPw().equals(KBProperties.DEFAULTPASSWORD)){
							mapperRtn.appendResult("chgPwd", "X");	
						}
						sysUser.setPw("");//不保存pw信息
						//创建用户session
						SessionUserBean sessionUserBean = new SessionUserBean();
						sessionUserBean.setSysUser(sysUser);
						sessionUserBean.setLoginTime(DateUtils.getNow());
						sessionUserBean.setSessionId(request.getSession().getId());
						
						//菜单json
						List list = new ArrayList();
						JSONArray jsonArray = new JSONArray();
						if(sysUser.getEmail()!= null && Md5.getPassword(sysUser.getEmail()).equals(KBProperties.SYSSUPERADMIN)){//超管
							//设置sessionUserBean中的sysUser－company为空，但不改用户表的company
//							sessionUserBean.getSysUser().setCompany("");
							Map conditions = new HashMap();
							conditions.put("isMenu", "10");
							list = iSysPopService.getAll(null, conditions);
						}else{
							Map conditions = new HashMap();
							list = iSysPopService.getMenu(sysUser.getFdRoleId());
						}
						
						if (list.size() > 0) {
							jsonArray = JSONArray.fromObject(list);
							sessionUserBean.setMenuJson(jsonArray.toString());
						}
						
						//session保存
						session.setAttribute("userSession", sessionUserBean);
						//记录登录信息
					}else{
						mapperRtn = ResultMapper.generateFailure();
						mapperRtn.appendResult("message", "用户匹配错误!");										
					}
//				}else{
//					mapperRtn.appendResult("message", "验证码错误!");
//				}
//			}else{
//				mapperRtn.appendResult("message", "验证码失效!");
//			}
			
			
			
		}
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：保存对象 自动赋予company
	*@param sysUser
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2013-11-15 下午4:20:56 
	*/
	@RequestMapping(value = "/sysUser/saveByCompany", method = RequestMethod.POST)
	@ResponseBody
	public String saveByCompany(HttpServletRequest request,@Valid @ModelAttribute("sysUser") SysUser sysUser,BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			boolean  flag = false;
			if(null != sysUser.getName()){
				sysUser.setName(sysUser.getName().toLowerCase().trim());
				String[] disallowStrs = KBProperties.DISALLOW.split(",");
				for (int i = 0; i < disallowStrs.length; i++) {
					if(sysUser.getName().contains(disallowStrs[i])){
						flag = true;
						break;
					}else{
						continue;
					}
				}
				
			}
			if(flag){
				//不允许创建
				mapper.appendResult("message", "不允许创建该用户名");
				return mapper.toJson();
			}
			//判断name 是否存在，如果存在不允许创建,如果是修改则无需传name，如果传了name会爆已存在。
			SysUser exist = iSysUserService.findByName(sysUser.getName());
			if(null != exist){
				mapper.appendResult("message", "已存在该用户不允许创建");
			}else{
				sysUser.setDocStatus("10");
				sysUser.setPw(null);
				sysUser.setCompany(UserUtils.getSessionUserBean(request).getSysUser().getCompany());
				mapper = iSysUserService.save(sysUser,request);
			}
			
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：保存对象
	*@param sysUser
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2013-11-15 下午4:20:56 
	*/
	@RequestMapping(value = "/sysUser/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,@Valid @ModelAttribute("sysUser") SysUser sysUser,BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			boolean  flag = false;
			if(null != sysUser.getName()){
				sysUser.setName(sysUser.getName().toLowerCase().trim());
				String[] disallowStrs = KBProperties.DISALLOW.split(",");
				for (int i = 0; i < disallowStrs.length; i++) {
					if(sysUser.getName().contains(disallowStrs[i])){
						flag = true;
						break;
					}else{
						continue;
					}
				}
				
			}
			if(flag){
				//不允许创建
				mapper.appendResult("message", "不允许创建该用户名");
				return mapper.toJson();
			}
			//判断name 是否存在，如果存在不允许创建,如果是修改则无需传name，如果传了name会爆已存在。
			SysUser exist = iSysUserService.findByName(sysUser.getName());
			if(null != exist){
				mapper.appendResult("message", "已存在该用户不允许创建");
			}else{
				sysUser.setDocStatus("10");
				sysUser.setPw(null);
				mapper = iSysUserService.save(sysUser,request);
			}
			
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：删除对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午3:38:17 
	*/
	@RequestMapping(value = "/sysUser/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			mapper = iSysUserService.delete(docId);
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：查看对象
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午3:39:35 
	*/
	@RequestMapping(value = "/sysUser/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			SysUser sysUser = iSysUserService.findById(docId);
			sysUser.setPw("");
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", sysUser);
		}		
		return mapperRtn.toJson();
	}
	@RequestMapping(value = "/sysUser/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@Valid @ModelAttribute("sysUser") SysUser sysUser,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			List  sysUsers = iSysUserService.getPage(sysUser, pageBean,conditions);
			int totalCount =  iSysUserService.getPageCount(sysUser,conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData",sysUsers);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}		
		return mapperRtn.toJson();
	}
	@RequestMapping(value = "/sysUser/listExt", method = {RequestMethod.POST, RequestMethod.GET } )
	@ResponseBody
	public String listExt(HttpServletRequest request,@Valid @ModelAttribute("start") String start,@Valid @ModelAttribute("limit") String limit,@Valid @ModelAttribute("sorgId") String sorgId,@Valid @ModelAttribute("sname") String sname,@Valid @ModelAttribute("sysUser") SysUser sysUser,@Valid @ModelAttribute("pageBean") PageBean pageBean,BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if(errors.hasErrors()){			
			mapperRtn = WebUtils.getMapper4Errors(errors);
		}else{
			Map conditions = new HashMap();
			conditions.put("sname", sname);
			conditions.put("orgId", sorgId);
			//conditions.put("company", UserUtils.getSessionUserBean(request).getSysUser().getCompany());
			if(!"".equals(start) && !"".equals(limit)){
				pageBean.setIntPageIndex(StringUtils.String2Integer(start) !=0?(StringUtils.String2Integer(start)):0);
				pageBean.setIntPageSize(StringUtils.String2Integer(limit) !=0?(StringUtils.String2Integer(limit)):0);
			}else{
				pageBean.setIntPageIndex(0);
				pageBean.setIntPageSize(KBProperties.PAGESIZE);
			}
			
			List  list = iSysUserService.getPage(sysUser, pageBean,conditions);
			int totalCount =  iSysUserService.getPageCount(sysUser,conditions);
			
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("total", totalCount);
			mapperRtn.appendResult("root", list);
		}		
		return mapperRtn.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：更新状态
	*@param request
	*@param docId
	*@param docStatus
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午4:41:35 
	*/
	@RequestMapping(value = "/sysUser/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,@Valid @ModelAttribute("docStatus") String docStatus,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				SysUser sysUser = new SysUser();
				
				sysUser.setDocId(docId);
				sysUser.setDocStatus(docStatus);
				mapper = iSysUserService.save(sysUser,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：重置密码
	*@param request
	*@param docId
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-2 下午5:03:18 
	*/
	@RequestMapping(value = "/sysUser/rePw", method = RequestMethod.POST)
	@ResponseBody
	public String rePw(HttpServletRequest request,@Valid @ModelAttribute("docId") String docId,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			if(!StringUtils.isStringEmpty(docId)){
				SysUser sysUser = new SysUser();
				sysUser.setDocId(docId);
				sysUser.setPw(Md5.getPassword(KBProperties.DEFAULTPASSWORD));
				mapper = iSysUserService.save(sysUser,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}
			
		}
		
		return mapper.toJson();
	}
	/**
	*@Author Rambo
	*@Desc：修改密码
	*@param request
	*@param oldPw
	*@param newPw
	*@param errors
	*@return TODO
	*@Version  SysUserController.java,v 1.1 2014-9-5 下午2:45:45 
	*/
	@RequestMapping(value = "/sysUser/rePwMyself", method = RequestMethod.POST)
	@ResponseBody
	public String rePwMyself(HttpServletRequest request,@Valid @ModelAttribute("oldPw") String oldPw,@Valid @ModelAttribute("newPw") String newPw,BindingResult errors) {
		
		if(errors.hasErrors()){			
			mapper = WebUtils.getMapper4Errors(errors);
		}else{
			SysUser sysUser = iSysUserDao.findByPwAndName(Md5.getPassword(oldPw), UserUtils.getSessionUserBean(request).getSysUser().getName().toLowerCase().trim());
			if(null != sysUser ){
				sysUser.setPw(Md5.getPassword(newPw));
				mapper = iSysUserService.save(sysUser,request);
			}else{
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "密码验证无法通过!");
			}
			
			
		}
		
		return mapper.toJson();
	}
	
}
